package com.lmj.learnspringboot.aop;

import com.lmj.learnspringboot.enums.ResultCode;
import com.lmj.learnspringboot.model.result.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;

/**
 * @author: lmj
 * @version: GlobalExceptionHandler.java lmj v1.0 2021/8/8 01:53
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.error("发生参数校验异常！原因是：", e);
        return ErrorResult.fail(ResultCode.API_PARAM_EXCEPTION, e, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(ArithmeticException.class)
    public ErrorResult handleMethodException(ArithmeticException e, HttpServletRequest request) {
        log.error("发生意外，请同学联系管理员", e);
        return ErrorResult.fail(ResultCode.EXCEPTION, e, MessageFormat.format("发生意外，请同学联系管理员{0}", request.getRequestURI()));
    }

    @ExceptionHandler(Exception.class)
    public ErrorResult handleCommonException(Exception e, HttpServletRequest request) {
        log.error("未知异常，请同学联系管理员", e);
        return ErrorResult.fail(ResultCode.EXCEPTION, e, MessageFormat.format("发生意外，请同学联系管理员{0}", request.getRequestURI()));
    }
}


